package com.zlb.demo.service.impl;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zlb.demo.domain.FamilyInfo;
import com.zlb.demo.domain.FamilyMember;
import com.zlb.demo.domain.HouseInfo;
import com.zlb.demo.domain.vo.*;
import com.zlb.demo.exception.ServiceException;
import com.zlb.demo.mapper.FamilyInfoMapper;
import com.zlb.demo.service.IFamilyInfoService;
import com.zlb.demo.service.IFamilyMemberService;
import com.zlb.demo.service.IHouseInfoService;
import com.zlb.demo.util.Assert;
import com.zlb.demo.util.BeanCopyUtil;
import com.zlb.demo.util.PageUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;
import java.util.function.Function;
import java.util.stream.Collectors;

/**
 * @Description
 * @Author zlb
 * @Since 2024-03-19 21:58:42
 */
@Service
public class FamilyInfoServiceImpl extends ServiceImpl<FamilyInfoMapper, FamilyInfo> implements IFamilyInfoService {

    @Autowired
    private IFamilyMemberService familyMemberService;

    @Autowired
    private IHouseInfoService houseInfoService;

    @Override
    public Page<FamilyInfo> page(FamilyInfoQueryVO queryVO) {
        Page<FamilyInfo> page = new Page<>();
        page.setCurrent(PageUtil.getCurrent());
        page.setSize(PageUtil.getSize());
        // List<Integer> ids = baseMapper.getIdsByQyery(queryVO);
        // LambdaQueryWrapper<FamilyInfo> queryWrapper = Wrappers.lambdaQuery(FamilyInfo.class)
        //         .like(StrUtil.isNotEmpty(queryVO.getHouseholderName()), FamilyInfo::getHouseholderName, queryVO.getHouseholderName())
        //         .in(CollUtil.isNotEmpty(ids), FamilyInfo::getId, ids);
        return baseMapper.page(page, queryVO);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean deleteByIds(Long[] ids) {
        if (ids.length < 1) {
            throw new ServiceException("请至少选择一个!");
        }
        boolean bool = removeByIds(Arrays.asList(ids));
        familyMemberService.remove(Wrappers.lambdaQuery(FamilyMember.class).in(FamilyMember::getFamilyId, ids));
        houseInfoService.remove(Wrappers.lambdaQuery(HouseInfo.class).in(HouseInfo::getFamilyId, ids));
        return bool;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean save(FamilyInfoSaveVO vo) {
        FamilyInfo familyInfo = BeanCopyUtil.copyObject(vo, FamilyInfo.class);
        // 数据校验
        Assert.isNull(familyInfo.getHouseNo(), "户编号为空,请检查后填写!");
        Assert.isNull(familyInfo.getHouseholderName(), "户主姓名为空,请检查后填写!");
        Assert.isNull(familyInfo.getHouseAddress(), "户所在地为空,请检查后填写!");
        // 所有校验完成,存入数据
        boolean bool = this.saveOrUpdate(familyInfo);
        List<FamilyMember> familyMembers = vo.getFamilyMembers();
        if (CollUtil.isNotEmpty(familyMembers)) {
            // 房屋基本信息主键回填
            familyMembers.forEach(item -> item.setFamilyId(familyInfo.getId()));
            long count = familyMembers.stream().filter(item -> StrUtil.equals(item.getMemberRelation(), "户主")).count();
            if (count > 1) {
                throw new ServiceException("选择了多个户主,请检查并重新选择!");
            }
            familyMemberService.saveOrUpdateBatch(familyMembers);
        }
        List<HouseInfo> houseInfos = vo.getHouseInfos();
        if (CollUtil.isNotEmpty(houseInfos)) {
            houseInfos.forEach(item -> {
                item.setFamilyId(familyInfo.getId());
                // 权属人ID转换
                Long owner = item.getOwner();
                item.setOwner(Optional.ofNullable(familyMembers.stream().filter(x -> x.getKey() == item.getOwner()).collect(Collectors.toList())).map(x -> x.get(0)).map(x -> x.getId()).orElse(owner));
            });
            houseInfoService.saveOrUpdateBatch(houseInfos);
        }

        return bool;
    }

    @Override
    public DetailVO detail(Long id) {
        Assert.isNull(id, "ID不能为空!");
        DetailVO detailVO = new DetailVO();
        detailVO.setFamilyInfo(baseMapper.selectById(id));
        List<FamilyMember> familyMemberList = familyMemberService.list(Wrappers.lambdaQuery(FamilyMember.class).in(FamilyMember::getFamilyId, id));
        // 重新构造key
        for (int i = 1; i <= familyMemberList.size(); i++) {
            familyMemberList.get(i - 1).setKey(Long.valueOf(i));
        }
        List<HouseInfo> houseInfoList = houseInfoService.list(Wrappers.lambdaQuery(HouseInfo.class).in(HouseInfo::getFamilyId, id));
        if (CollUtil.isNotEmpty(familyMemberList)) {
            Map<String, FamilyMember> maps = familyMemberList.stream().collect(Collectors.toMap(item -> StrUtil.toString(item.getId()), Function.identity(), (oldValue, newValue) -> oldValue));
            if (CollUtil.isNotEmpty(houseInfoList)) {
                houseInfoList.forEach(item -> {
                    // 再将新构造的key放入房屋权属人
                    item.setOwner(Optional.ofNullable(item.getOwner()).map(i -> maps.get(StrUtil.toString(i))).map(x -> x.getKey()).orElse(null));
                    // item.setOwnerName(Optional.ofNullable(item.getOwner()).map(i -> maps.get(StrUtil.toString(i))).map(x -> x.getName()).orElse(null));
                });
            }
        }
        detailVO.setFamilyMemberList(familyMemberList);
        detailVO.setHouseInfoList(houseInfoList);
        return detailVO;
    }
}
